package com.fly.hello.service.impl;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomUtils;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fly.core.JsonResult;
import com.fly.hello.service.AsynService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AsynServiceImpl implements AsynService
{
    @Autowired
    private RestTemplate restTemplate;
    
    @Async
    @Override
    public void test(String traceId)
    {
        try
        {
            ThreadContext.put("id", traceId);
            log.info("async start");
            for (int i = 0; i < 10; i++)
            {
                log.info("i = {}", i);
                TimeUnit.MILLISECONDS.sleep(500);
            }
            log.info("async end");
        }
        catch (InterruptedException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    @Override
    @SuppressWarnings("rawtypes")
    public void call()
    {
        String url = "http://127.0.0.1:8080/upload2";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("file", new ClassPathResource("data/pic/001.jpg"));
        params.add("id", "1");
        params.add("name", "girl");
        params.add("sex", "F");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JsonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, JsonResult.class);
        log.info("ResponseEntity={}", responseEntity);
    }
    
    @Override
    public void test(String key, String taskId)
    {
        try
        {
            log.info("start");
            
            // 抛出异常
            if (RandomUtils.nextBoolean())
            {
                key = "" + 4 / 0;
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            log.info("清理现场");
        }
    }
}
